package stock.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import stock.properties.WxMpProperties;
import stock.utils.HttpsUtil;

import java.util.Map;

@Service
public class WechatServiceImpl {

    @Autowired
    private WxMpProperties wxMpProperties;

    /**
     * 公众号 获取access_token api url
     */
    public static String apiAccessTokenUrl ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    /**
     * 公众号 获取用户信息 api url
     */
    public static String apiUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    /**
     * 公众号 获取access_token
     */
    public Object getAccessToken(String code){
        String url = String.format(apiAccessTokenUrl, wxMpProperties.getAppId(), wxMpProperties.getSecret(),code);
        //通过http请求获取结果

        String response = HttpsUtil.httpsRequestToString(url,"GET",null);
        //"{\"access_token\":\"70_YflCV2JfBu0aWldgq26O2-yxfHoZn1aduorJwSz8nobCoY71rAo7Zvl4ikcul5bTdmlawBlUy5_5HpHghAWoen-UJv3Xma5Y-mv0HOlEznc\",\"expires_in\":7200,\"refresh_token\":\"70_EtjPyf2PSu7iHvnWyGi7xvOg8EykffASK8QRnTDWxqUh_hU_QLdOkJDWMr3fFXmJkoguisDGVADWfTbBc5PatfQnOvaV8EGeLu_YSFwrEeQ\",\"openid\":\"oYUCe6uNmTNsiR9RQb1ubKy7bWt4\",\"scope\":\"snsapi_userinfo\",\"unionid\":\"orl9_wUrXWQVQfSHj0Q8dE0iteLM\"}"
        //System.out.println("========="+response);
        Map<String,String> result = (Map<String, String>) JSONObject.parse(response);
        return result;
    }
    /**
     * 公众号 获取用户信息
     */
    public Object getUserInfo(String accessToken, String openid){
        String url = String.format(apiUserInfoUrl,accessToken,openid);
        String response = HttpsUtil.httpsRequestToString(url,"GET",null);
        Map<String,String> result = (Map<String, String>) JSONObject.parse(response);
        return result;
    }
}
